package cn.tedu.vrd.filter;

import cn.tedu.vrd.vo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns = {"/send.html","/admin.html"})
public class MyFilter implements Filter {
    public void destroy() {//过滤器销毁时执行的方法
    }

    //执行Controller方法之前和之后执行的方法
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //得到Session会话对象
        HttpSession session = request.getSession();
        //得到登录的用户对象
        User u = (User) session.getAttribute("u");
        if (u!=null){//登录了
            chain.doFilter(req, resp);
        }else{ //让客户端跳转到登录页面
            response.sendRedirect("/login.html");
        }
    }

    //过滤器初始化时执行的方法
    public void init(FilterConfig config) throws ServletException {

    }

}
